#include <unistd.h>
#include <string.h>
#include <errno.h>
#include "SignalEvtHandle.h"
#define OK					0
#define ERROR				-1
typedef intptr_t ngx_int_t;
typedef int ngx_err_t;
typedef struct {
	int     signo;
	char   *signame;
	char   *name;
	void(*handler)(int signo, siginfo_t *siginfo, void *ucontext);
} ngx_signal_t;
static void signal_handler(int signo, siginfo_t *siginfo, void *ucontext);


ngx_signal_t  signals[] = {
	{ signal_value(RECONFIGURE_SIGNAL),
	"SIG" value(RECONFIGURE_SIGNAL),
	"reload",
	signal_handler },

	{ signal_value(REOPEN_SIGNAL),
	"SIG" value(REOPEN_SIGNAL),
	"reopen",
	signal_handler },

	{ signal_value(NOACCEPT_SIGNAL),
	"SIG" value(NOACCEPT_SIGNAL),
	"",
	signal_handler },

	{ signal_value(TERMINATE_SIGNAL),
	"SIG" value(TERMINATE_SIGNAL),
	"stop",
	signal_handler },

	{ signal_value(SHUTDOWN_SIGNAL),
	"SIG" value(SHUTDOWN_SIGNAL),
	"quit",
	signal_handler },

	{ signal_value(CHANGEBIN_SIGNAL),
	"SIG" value(CHANGEBIN_SIGNAL),
	"",
	signal_handler },

	{ SIGALRM, "SIGALRM", "", signal_handler },

	{ SIGINT, "SIGINT", "", signal_handler },

	{ SIGIO, "SIGIO", "", signal_handler },

	{ SIGCHLD, "SIGCHLD", "", signal_handler },

	{ SIGSYS, "SIGSYS, SIG_IGN", "", NULL },

	{ SIGPIPE, "SIGPIPE, SIG_IGN", "", NULL },

	{ 0, NULL, "", NULL }
};

bool init_signals()
{
	ngx_signal_t      *sig;
	struct sigaction   sa;

	for (sig = signals; sig->signo != 0; sig++) {
		memset(&sa, 0, sizeof(struct sigaction));

		if (sig->handler) {
			sa.sa_sigaction = sig->handler;
			sa.sa_flags = SA_SIGINFO;			
		}
		else {
			sa.sa_handler = SIG_IGN;
		}		
		sigemptyset(&sa.sa_mask);
		if (sigaction(sig->signo, &sa, NULL) == -1) {
			return false;
		}
	}

	return true;
}

static void signal_handler(int signo, siginfo_t *siginfo, void *ucontext)
{
	char            *action;
	ngx_int_t        ignore;
	ngx_err_t        err;
	ngx_signal_t    *sig;

	ignore = 0;

	err = errno;

	for (sig = signals; sig->signo != 0; sig++) {
		if (sig->signo == signo) {
			break;
		}
	}

	action = "";

	switch (signo) {

	case signal_value(SHUTDOWN_SIGNAL):
		break;

	case signal_value(TERMINATE_SIGNAL):
	case SIGINT:
		break;

	case signal_value(NOACCEPT_SIGNAL):
		break;

	case signal_value(RECONFIGURE_SIGNAL):
		//printf("rev signal hup\n");		
		break;

	case signal_value(REOPEN_SIGNAL):
		break;

	case signal_value(CHANGEBIN_SIGNAL):
		break;

	case SIGALRM:
		break;

	case SIGIO:
		break;

	case SIGCHLD:
		break;
	}
}
